﻿using FreeDream.Model;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;

namespace FreeDream.WebApi.Filter
{
    public class ExceptionHandlingAttribute : ExceptionFilterAttribute
    {
        private readonly ILogger<ExceptionHandlingAttribute> _logger;
        /// <summary>
        /// 记录全局统一错误日志
        /// </summary>
        /// <param name="logger"></param>
        public ExceptionHandlingAttribute(ILogger<ExceptionHandlingAttribute> logger)
        {
            _logger = logger;
        }
        /// <summary>
        /// 统一错误处理 返回固定格式数据 同时写入数据库
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task OnExceptionAsync(ExceptionContext context)
        {
            var routeValueDictionary = context.RouteData.Values;
            _logger.LogError(context.Exception.Message, context.Exception);
            context.Result = new OkObjectResult(new BaseResponse { code = ResponseCode.GOLABLERROR, Message = context.Exception.Message, timespan = DateTime.Now });
            return base.OnExceptionAsync(context);
        }
    }
}
